package com.cicoding.controller;

import com.cicoding.utils.*;
import org.apache.tools.ant.taskdefs.Zip;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.*;

@RestController
public class DocControllor {

    @GetMapping("/word02")
    public String getWord02() throws Exception {
        //市级开卡数据
        Map<String, String> params = new HashMap<>();
        params.put("d1", "系统生成的测试片段");

        Integer templateFileNumber = 1;
        String word = String.valueOf(DocUtils.createWord(null, params));
        return word;
    }

    @GetMapping("/word03")
    public String getWord03() throws Exception {
        //市级开卡数据
        Map<String, String> params = new HashMap<>();
        params.put("d1", "系统生成的测试片段");

        Integer templateFileNumber = 1;
        String word = String.valueOf(DocUtils.testCreateWord(params));
        return word;
    }

    @PostMapping("/upload")
    public String uploadFile(@RequestParam("excelFile") MultipartFile excelMultipartFile,
                             @RequestParam("wordFile") MultipartFile wordMultipartFile) throws Exception {
        //市级开卡数据
        Map<String, Object> params = new HashMap<>();
        params.put("d1", "系统生成的测试片段");

        File excelFile = FileUtil.coverMultipartFile2File(excelMultipartFile);
        List<Map<String, String>> maps = ExcelUtils.readSheet1ToListMap(excelFile);

        File file = FileUtil.coverMultipartFile2File(wordMultipartFile);
        File docFile = DocUtils.coverDocToXml(file);
        List<File> files = new ArrayList<>();
        for(int i = 0; i < maps.size(); i++) {
            File word = DocUtils.createWord(docFile, maps.get(i));
            File pdf = DocUtils.coverDocToPdf(word);
            files.add(word);
            files.add(pdf);
        }
        File zipFile = File.createTempFile(UUID.randomUUID().toString(), ".zip");
        ZipUtils.zipFiles(files, zipFile);
        return zipFile.getAbsolutePath();
    }

    @PostMapping("/uploadExcel")
    public String uploadExcel(@RequestParam("file") MultipartFile multipartFile) throws Exception {
        File file = FileUtil.coverMultipartFile2File(multipartFile);
        ExcelUtils.readSheet1ToListMap(file);
        return "success";
    }

    @PostMapping("/mergeFile")
    public String mergeFile(@RequestParam("excelFile") MultipartFile excelMultipartFile,
                             @RequestParam("wordFile") MultipartFile wordMultipartFile) throws Exception {
        File excelFile = FileUtil.coverMultipartFile2File(excelMultipartFile);
        File wordFile = FileUtil.coverMultipartFile2File(wordMultipartFile);
        File file = PdfUtils.mergePdf(excelFile, wordFile);
        return file.getAbsolutePath();
    }
}
